package controller;

import java.util.ArrayList;

import util.MoveType;
import entity.Board;
import entity.Move;
import entity.Poem;
import entity.Row;
import entity.Word;
import gui.BoardApplication;

/**
 * This is the disconnect controller.
 */
public class DisconnectController {
	private Board board;
	private BoardApplication gui;
	
	/**
	 * Constructor of disconnect controller.
	 */
	public DisconnectController(BoardApplication gui, Board board){
		this.board = board;
		this.gui = gui;
	}

	/**
	 * Disconnect a word from a pome.
	 * Remove the word from the original row and poem.
	 */
	public void disconnect(Word word, boolean checkpoint){
		Poem poemFrom = board.poemThatContains(word);
		Row rowFrom = poemFrom.rowThatContains(word);
		
		if(rowFrom.getWords().size() == 1){
			disconnect(rowFrom, checkpoint);
		}else{
			Move move = new Move(MoveType.DISCONNECT, checkpoint);
			move.addOldItem(poemFrom);
			
			int index = rowFrom.getWords().indexOf(word);
			
			if(poemFrom.getRows().size() == 1 && rowFrom.getWords().size() == 2){
				board.getPoems().remove(poemFrom);

				move.addNewItem(rowFrom.getWords().get(0));
				move.addNewItem(rowFrom.getWords().get(1));
			}else if(index == 0 || index == rowFrom.getWords().size() - 1){
				rowFrom.removeWord(word);

				move.addNewItem(poemFrom);
				move.addNewItem(word);
			}
			
			board.addMove(move);
		}
	}

	/**
	 * Disconnect a row from a poem. 
	 * Three new poems will be created.
	 * The original poem will be removed.
	 */
	public void disconnect(Row r, boolean checkpoint){
		Poem poemFrom = board.poemThatContains(r);
		
		Move move = new Move(MoveType.DISCONNECT, checkpoint);
		move.addOldItem(poemFrom);

		ArrayList<Row> rowsBefore = new ArrayList<Row>();
		ArrayList<Row> rowsAfter = new ArrayList<Row>();
		int index = poemFrom.getRows().indexOf(r);
		
		for(int i = 0; i < poemFrom.getRows().size(); i++){
			if(i < index){
				rowsBefore.add(poemFrom.getRows().get(i));
			}else if(i > index){
				rowsAfter.add(poemFrom.getRows().get(i));
			}
		}

		if(rowsBefore.size() > 0){
			Poem p = new Poem(Poem.nextId(), rowsBefore);
			board.getPoems().add(p);
			p.rearrange();
			
			move.addNewItem(p);
		}

		if(rowsAfter.size() > 0){
			Poem p = new Poem(Poem.nextId(), rowsAfter);
			board.getPoems().add(p);
			p.rearrange();
			
			move.addNewItem(p);
		}

		board.getPoems().remove(poemFrom);
		
		if(r.getWords().size() > 1){
			Poem newPoem = new Poem(Poem.nextId(), r);
			board.getPoems().add(newPoem);
			newPoem.rearrange();
			
			move.addNewItem(newPoem);
		}
		
		board.addMove(move);
	}
	
	/**
	 * Return board.
	 */
	public Board getBoard() {
		return board;
	}
}
